// proxy 代理
let objs = {
  a: 1,
  b: {
    c: 2
  }
}
let handler = {
  get (target, property, receiver) {
    let res = Reflect.get(target, property, receiver)
    console.log(`proxy -- target: ${JSON.stringify(target)} property: ${property}  get: ${JSON.stringify(res)}`)
    return res
  },
  set (target, property, value, receiver) {
    let res = Reflect.set(target, property, value, receiver)
    console.log(`proxy target: ${JSON.stringify(target)} value: ${value} property: ${property} -- set: ${JSON.stringify(res)}`)
    return res
  }
}
// const objProxy = new Proxy(obj,handler)
// console.log(objProxy.a)
// objProxy.a++
// console.log(`objProxy.a++ :`, objProxy.a)
// objProxy.a = 10
// console.log(`objProxy.a = 10 :`, objProxy.a)
// objProxy.b.c = 4
// console.log(objProxy)

// const arr = [1]
// const arrProxy = new Proxy(arr, handler)
// console.log(arrProxy)
// console.log(arrProxy[0])
// arrProxy[0]++
// console.log(`arrProxy[0]++ :`, arrProxy[0])
// arrProxy[0] = 10
// console.log(`arrProxy[0] = 10 :`, arrProxy[0])
// arrProxy.push(100)
// console.log(arrProxy)
// arrProxy.splice(0,1,999)
// console.log(arr)
function isObject(val){
  return typeof val === "object" && val !== null
}
function myProxy (target) {
  console.log(target)
  let handler = {
    get (target, property, receiver) {
      let res = Reflect.get(target, property, receiver)
      console.log(`proxy -- target: ${JSON.stringify(target)} property: ${property}  get: ${JSON.stringify(res)}`)
      // 判断获取的值是否是对象，如果是对象也要让它的get 和 set 也被拦截
      if(isObject(res)) {
        return myProxy(res)
      }
      return res
    },
    set (target, property, value, receiver) {
      let res = Reflect.set(target, property, value, receiver)
      console.log(`proxy target: ${JSON.stringify(target)} value: ${value} property: ${property} -- set: ${JSON.stringify(res)}`)
      return res
    }
  }
  return new Proxy(target,handler)
}
// const objProxy = myProxy(obj)
const arr = [1]
const arrProxy = myProxy(arr)
console.log(arrProxy)
console.log(arrProxy[0])
arrProxy[0]++
console.log(`arrProxy[0]++ :`, arrProxy[0])
arrProxy[0] = 10
console.log(`arrProxy[0] = 10 :`, arrProxy[0])
arrProxy.push(100)
console.log(arrProxy)
arrProxy.splice(0,1,999)
console.log(arr)
